

/**
 * ManageController
 *
 * @author glory.xu
 */

import { Post, Get, Prefix } from 'egg-shell-decorators';
import BaseController from '../base';

import fs = require('fs');
import path = require('path');
const awaitWriteStream = require('await-stream-ready').write;
import sendToWormhole = require('stream-wormhole');
import dayjs = require('dayjs');


@Prefix('manage')
export default class ManageController extends BaseController {

  @Get('/login')
  public async login() {
    const { ctx } = this;
    await ctx.render('manage/login.html');
  }


  @Post('/doLogin')
  async doLogin() {
    const { ctx } = this;
    const user = ctx.request.body;
    if (user && user.username) {


      const res: any = await ctx.service.user.getByUserName(user.username);
      console.log(res);

      if (res && res.role === 'admin' && res.password === user.password) {
        ctx.session.username = user.username;

        ctx.redirect('/manage/main');
        return;
      }


    }
    ctx.redirect('/manage/login?err=login');
  }

  @Get('/logout')
  async logout() {
    const { ctx } = this;
    ctx.session.username = '';
    ctx.redirect('/manage/login');
  }


  @Get('/main')
  public async main() {
    const { ctx } = this;
    const username = ctx.session.username;
    const liId = ctx.params.liId;
    await ctx.render('manage/main.html', { username, liId });
  }

  @Post('/upload')
  public async upload({ request: { query } }) {
    const stream = await this.ctx.getFileStream();
    const uplaodBasePath = 'app/public/uploads';
    // 生成文件名
    const filename = `${Date.now()}${Number.parseInt((Math.random() * 1000).toString())}${path.extname(stream.filename).toLocaleLowerCase()}`;
    // 生成文件夹
    const dirname = dayjs(Date.now()).format('YYYY/MM/DD');
    function mkdirsSync(dirname) {
      if (fs.existsSync(dirname)) {
        return true;
      }
      if (mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname);
        return true;
      }

    }
    mkdirsSync(path.join(uplaodBasePath, dirname));
    // 生成写入路径
    const target = path.join(uplaodBasePath, dirname, filename);
    // 写入流
    const writeStream = fs.createWriteStream(target);
    try {
      await awaitWriteStream(stream.pipe(writeStream));
    } catch (err) {
      await sendToWormhole(stream);
      // this.error();
    }

    //
    // upload?CKEditor=editor1&CKEditorFuncNum=0&langCode=zh-cn
    // CKEditor回调
    const { CKEditorFuncNum } = query;
    const imageContextPath:string = '/public/uploads/' + dirname + '/' + filename;
    let jsStr = '';
    jsStr = '<script type="text/javascript">';
    jsStr = jsStr + 'window.parent.CKEDITOR.tools.callFunction(' + CKEditorFuncNum + ",'" + imageContextPath + "',''" + ')';
    jsStr = jsStr + '</script>';

    this.ctx.body = jsStr;


  }


  @Post('/uploadSingle')
  public async uploadSingle() {
    const stream = await this.ctx.getFileStream();
    const uplaodBasePath = 'app/public/uploads';
    // 生成文件名
    const filename = `${Date.now()}${Number.parseInt((Math.random() * 1000).toString())}${path.extname(stream.filename).toLocaleLowerCase()}`;
    // 生成文件夹
    const dirname = dayjs(Date.now()).format('YYYY/MM/DD');
    function mkdirsSync(dirname) {
      if (fs.existsSync(dirname)) {
        return true;
      }
      if (mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname);
        return true;
      }

    }
    mkdirsSync(path.join(uplaodBasePath, dirname));
    // 生成写入路径
    const target = path.join(uplaodBasePath, dirname, filename);
    // 写入流
    const writeStream = fs.createWriteStream(target);
    try {
      await awaitWriteStream(stream.pipe(writeStream));
    } catch (err) {
      await sendToWormhole(stream);
      // this.error();
    }

    const imageContextPath:string = '/public/uploads/' + dirname + '/' + filename;
    this.success(imageContextPath);


  }


}
